package main

import (
	"context"
	"flag"
	"fmt"
	"gitee.com/go_task/metrics"
	"github.com/golang/glog"
	"github.com/prometheus/client_golang/prometheus/promhttp"
	"io"
	"math/rand"
	"net/http"
	_ "net/http/pprof"
	"os"
	"os/signal"
	"syscall"
	"time"
)

func main() {
	flag.Set("v", "4")
	glog.V(2).Info("Starting http server...")
	metrics.Register()
	mux := http.NewServeMux()
	mux.HandleFunc("/hello", rootHandler)
	mux.HandleFunc("/healthz", healthz)
	mux.Handle("/metrics", promhttp.Handler())

	srv := http.Server{
		Addr:    ":80",
		Handler: mux,
	}
	done := make(chan os.Signal, 1)
	signal.Notify(done, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)

	go func() {
		if err := srv.ListenAndServe(); err != nil && err != http.ErrServerClosed {
			glog.Fatalf("listen: %s\n", err)
		}
	}()
	glog.Info("Server Started")
	<-done
	glog.Info("Server Stopped")
	ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
	defer func() {
		// extra handling here
		cancel()
	}()

	if err := srv.Shutdown(ctx); err != nil {
		glog.Fatalf("Server Shutdown Failed:%+v", err)
	}
	glog.Info("Server Exited Properly")
}

func randInt(min int, max int) int {
	rand.Seed(time.Now().UTC().UnixNano())
	return min + rand.Intn(max-min)
}

func rootHandler(w http.ResponseWriter, r *http.Request) {
	timer := metrics.NewTimer()
	defer timer.ObserveTotal()
	randInt := rand.Intn(2000)
	time.Sleep(time.Millisecond * time.Duration(randInt))
	w.Write([]byte(fmt.Sprintf("<h1>%d<h1>", randInt)))
}

// 4.当访问 localhost/healthz 时，应返回200
func healthz(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(200)
	io.WriteString(w, "ok\n")
}

//func rootHandler(w http.ResponseWriter, r *http.Request) {
//	// 获取中系统环境变量
//	// 1.接收客户端 request，并将 request 中带的 header 写入 response header
//	for k, v := range r.Header {
//		arr1Byte, _ := json.Marshal(v)
//		arr1Str := string(arr1Byte)
//		w.Header().Set(k, arr1Str)
//		io.WriteString(w, fmt.Sprintf("%s=%s\n", k, v))
//	}
//	// 2.读取当前系统的环境变量中的 VERSION 配置，并写入 response header
//	version := os.Getenv("VERSION")
//	addrs, err := net.InterfaceAddrs()
//	if err != nil {
//	}
//	arss := make([]string, 0)
//	for _, address := range addrs {
//		// 检查ip地址判断是否回环地址
//		if ipnet, ok := address.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
//			if ipnet.IP.To4() != nil {
//				arss = append(arss, ipnet.IP.String())
//			}
//		}
//	}
//	// 3.Server 端记录访问日志包括客户端 IP，HTTP 返回码，输出到 server 端的标准输出//
//	code := 200
//	fmt.Printf("客户端 {IP：%s,状态: %d} \n", r.RemoteAddr, code)
//	// 设置请求头信息
//	w.Header().Set("VERSION", version)
//	// 设置状态码
//	w.WriteHeader(200)
//}
